<?php

namespace App\B2BProject\Custom;

use App\B2BProject\Custom\Provider\CounterOffer;
use App\B2BProject\Custom\Purchaser\CounterEnquiry;
use App\B2BProject\Exception\UserTypeException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Builder;

/**
 * Class Member
 *
 * 网站成员模型类
 *
 * @package App\B2BProject\Custom
 */
class Member extends Model implements AuthenticatableContract,
                                      AuthorizableContract,
                                      CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    const PROVIDER_USER  = 1;
    const PURCHASER_USER = 2;

    /**
     * 允许直接填充的字段
     *
     * @var array
     */
    protected $fillable = ['user', 'email', 'password', 'class', 'status'];

    /**
     * 直接读取时会被隐藏的字段
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function information()
    {
        return $this->hasOne('App\B2BProject\Custom\MemberInformation', 'member_id', 'id');
    }

    /**
     * 用户关联的店铺
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function store()
    {
        return $this->hasOne('App\B2BProject\Custom\Business\Store', 'member_id', 'id');
    }

    /**
     * 返回当前用户的（报盘、询盘）回复信息
     *
     * 对于供应商，返回的是其对采购商的询盘信息的回复集合，相反，对于采购商返回的则是其对供应商的报盘信息的回复集合
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function counters()
    {
        if ($this->getAttribute('class') == self::PROVIDER_USER) {
            return $this->hasMany('App\B2BProject\Custom\Purchaser\CounterEnquiry', 'member_id', 'id');
        } else {
            return $this->hasMany('App\B2BProject\Custom\Provider\CounterOffer', 'member_id', 'id');
        }
    }

    /**
     * 获取当前用户收到的（询盘、报盘）回复信息
     *
     * @return CounterOffer|CounterEnquiry
     */
    public function receiveCounters()
    {
        if ($this->getAttribute('class') == self::PROVIDER_USER) {
            return CounterOffer::whereHas('offer', function (Builder $builder) {
                $builder->where('member_id', \Auth::id());
            });
        } else {
            return CounterEnquiry::whereHas('enquiry', function (Builder $builder) {
                $builder->where('member_id', \Auth::id());
            });
        }
    }

    /**
     * 返回当前用户发布的信息（报盘、询盘）集合
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function publishes()
    {
        if ($this->getAttribute('class') == self::PROVIDER_USER) {
            return $this->hasMany('App\B2BProject\Custom\Provider\Offer', 'member_id', 'id');
        } else {
            return $this->hasMany('App\B2BProject\Custom\Purchaser\Enquiry', 'member_id', 'id');
        }
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function address()
    {
        return $this->hasMany('App\B2BProject\Custom\Business\Address', 'member_id', 'id');
    }

    /**
     * 返回当前用户是否为供应商
     *
     * @return bool
     */
    public function isProvider()
    {
        return $this->class == self::PROVIDER_USER ?: false;
    }

    /**
     * 返回当前用户是否为采购商
     *
     * @return bool
     */
    public function isPurchaser()
    {
        return $this->class == self::PURCHASER_USER ?: false;
    }

    /**
     * 返回当前用户发布的信息（供应商、采购商）集合
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function getMemberIdPublishes()
    {
        if ($this->getAttribute('class') == self::PROVIDER_USER) {
            return $this->hasMany('App\B2BProject\Custom\AuthorizationRequest', 'provider_id', 'id');
        } else {
            return $this->hasMany('App\B2BProject\Custom\AuthorizationRequest', 'purchaser_id', 'id');
        }
    }

    /**
     * 获取购物车数据
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function shoppingCart()
    {
        return $this->hasMany('App\B2BProject\Custom\Purchaser\ShoppingCart', 'member_id', 'id');
    }

    /**
     * 作为供应商，获取全部授权申请列表
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function providerAuthorizationRequests()
    {
        return $this->hasMany('App\B2BProject\Custom\AuthorizationRequest', 'provider_id', 'id');
    }

    /**
     * 作为采购商，获取全部授权申请列表
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function purchaserAuthorizationRequests()
    {
        return $this->hasMany('App\B2BProject\Custom\AuthorizationRequest', 'purchaser_id', 'id');
    }

    /**
     * 快速取得授权商品列表，通常是用于查看分销关系时使用
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
     */
    public function providerLicensedGoods()
    {
        return $this->hasManyThrough('App\B2BProject\Custom\Business\LicensedGood',
            'App\B2BProject\Custom\AuthorizationRequest', 'provider_id', 'authorization_id');
    }

    /**
     * （对于采购商）获取当前用户订单列表
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function orders()
    {
        if ($this->isProvider()) {
            throw new UserTypeException;
        }

        return $this->hasMany('App\B2BProject\Custom\Business\Order', 'member_id', 'id');
    }

    /**
     * （对于供应商）获取当前用户订单列表
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function purchaserOrders()
    {
        if ($this->isPurchaser()) {
            throw new UserTypeException;
        }

        return $this->hasMany('App\B2BProject\Custom\Business\Order', 'provider_id', 'id');
    }

    /**
     * 获取增值税发票资质信息
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function VAT()
    {
        if ($this->isProvider()) {
            throw new UserTypeException;
        }

        return $this->hasOne('App\B2BProject\Custom\Purchaser\ValueAddedTaxInvoiceQualification', 'member_id', 'id');
    }

    /**
     * 获取当前用户发布或回复的咨询
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function issues()
    {
        return $this->hasMany('App\B2BProject\Custom\Business\Issue', 'member_id', 'id');
    }

    /**
     * 获取当前供应商、采购商的短消息列表
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function messages()
    {
        return $this->hasMany('App\B2BProject\Custom\Message', 'member_id', 'id');
    }

    /**
     * 查询供应商
     *
     * @param Builder $builder
     *
     * @return $this
     */
    public function scopeSelectProvider(Builder $builder)
    {
        return $builder->where('class', static::PROVIDER_USER);
    }

    /**
     * 查询采购商
     *
     * @param Builder $builder
     *
     * @return $this
     */
    public function scopeSelectPurchaser(Builder $builder)
    {
        return $builder->where('class', static::PURCHASER_USER);
    }

    /**
     * 用户发票
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function invoice()
    {
        return $this->hasMany('App\B2BProject\Custom\Business\Invoice', 'member_id', 'id');
    }
}
